<?php

class ChangePasswordForm extends CFormModel {

    public $oldPassword;
    public $newPassword;
    public $newPassword_repeat;
    public $_user;

    public function rules() {
        return array(
            array(
                'oldPassword', 'compareOldPassword'
            ),
            array(
                'oldPassword, newPassword, newPassword_repeat', 'required',
                'message' => '(*) {attribute} là bắt buộc.',
            ),
            array(
                'newPassword_repeat', 'compare',
                'compareAttribute' => 'newPassword',
                'message' => 'Mật khẩu không khớp.',
            ),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'oldPassword' => 'Email',
            'newPassword' => 'Mật khẩu',
            'newPassword_repeat' => 'Xác nhận mật khẩu',
        );
    }

    public function compareOldPassword($attribute, $params) {
        if (md5($this->oldPassword) !== $this->_user->password) {
            $this->addError($attribute, 'Mật khẩu cũ không chính xác.');
        }
    }

    public function init() {
        $this->_user = User::model()->findByPk(Yii::app()->user->id);
    }

    public function changePassword() {
        $this->_user->password = md5($this->newPassword);
        if ($this->_user->save())
            return true;
        return false;
    }
}
